<?php
declare (strict_types = 1);

namespace app\controller\backend\site;

use app\exception\LogicException;
use app\service\logic\backend\site\SiteService;
use app\service\logic\backend\system\AdminService;
use app\service\logic\common\tool\UploadService;
use app\validate\common\site\SiteValidate;
use Exception;
use think\App;
use app\BaseController;
use think\facade\Cookie;
use think\facade\Log;
use think\facade\View;
use think\response\Json;
use think\response\Redirect;

class SiteController extends BaseController
{
    protected $service;

    protected $uploadService;

    protected $adminService;


    public function __construct(
        App $app, SiteService $service, UploadService $uploadService, AdminService $adminService
    ) {
        parent::__construct($app);

        $this->service = $service;
        $this->uploadService = $uploadService;
        $this->adminService = $adminService;
    }

    /**
     * 登录页面
     *
     * @return Redirect|\think\response\View
     */
    public function view()
    {
        $admin = auth('backend')->user();
        if ($admin) {
            // return redirect('/b/home/index.html');
            return redirect('/b/om/view.html');
        }
        View::assign('title', lang('backend.common view title'));
        return view('backend/site/login');
    }

    /**
     * 后台系统上传接口
     *
     * @return Json
     */
    public function upload()
    {
        $params = request()->only(['type']);
        $file = request()->file() ?? [];
        $this->validate($file, SiteValidate::class . '.file');
        $this->validate($params, SiteValidate::class . '.upload');

        $result = $this->uploadService->upload($params, $file);
        return amis([
            'value' => $result
        ]);
    }

    /**
     * 登录
     *
     */
    public function login()
    {
        $result = $this->universalLogin();
        $token = $result['token'];
        Cookie::set('token', $token, ['expire' => config('jwt.ttl')]);
        return amis([
            'user' => $result['user'],
            'token' => $token
        ], '登录成功');
    }

    /**
     * 账密
     *
     * @return array|mixed
     */
    private function universalLogin()
    {
        // 账密
        $params = $this->request->only(['relation_type', 'account', 'password']);
        $this->validate($params, SiteValidate::class . '.account');
        $params['relation_type'] = $params['relation_type'] ?? 1;

        $result = $this->service->login($params);
        event('AfterAdminLogin', ['id' => $result['user']['id'],  'token' => $result['token']]); // 可队列
        return $result;
    }

    /**
     * 退出
     *
     * @return Redirect
     */
    public function logout(): Redirect
    {
        try {
            $token = auth('backend')->token();
            $this->adminService->deleteAccessTokenByToken($token);
        } catch (Exception $e) {
            Log::debug('backendLogoutException: ' . $e->getMessage());
        }
        Cookie::delete('token');
        return redirect('/b/site/view.html');
    }
}
